package day2.test1;

import java.lang.reflect.Field;

public class RefilectDemo2 {
    public static void main(String[] args) throws Exception {
        //获取Person的Class对象
        Class personClass = Person.class;
        //Field[] getFields()获取所有public修饰的成员变量
        Field[] fields=personClass.getFields();
        for(Field field:fields){
            System.out.println("personClass.getFields():"+field);
        }
        System.out.println("---------------------------------");
        //获取成员变量a的值
        Field a = personClass.getField("a");
        Person p=new Person();
        Object value=a.get(p);
        System.out.println("a.get(p)"+value);
        //设置a的值
        a.set(p,"张三");
        System.out.println("a.set(p,\"张三\"):"+p);
        System.out.println("--------------------------------");
        //Field[] getDeclaredFields获取所有成员变量，不考虑修饰符
        Field[] declaredFields = personClass.getDeclaredFields();
        for(Field declaredField:declaredFields){
            System.out.println("personClass.getDeclaredFields():"+declaredField);
        }
        //Field getDeclaredField(String name)
        Field d = personClass.getDeclaredField("d");
        //忽略访问权限修饰符的安全检查
        d.setAccessible(true);
        Object value2 = d.get(p);
        System.out.println("d.get(p)"+value2);
    }
}
